﻿using CqCore.Commands;
using CqCore.Redis;
using SuperShopInfrastructure.Models.Comment;
using SuperShopInfrastructure.Static;
using SuperShopRepository;
using SuperShopService.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopService.Services
{
    public class CommentService : ICommentService
    {
        private readonly CommentRepository commentRepository;
        private readonly IRedisService redisService;

        public CommentService(
            CommentRepository commentRepository,
            IRedisService redisService)
        {
            this.commentRepository = commentRepository;
            this.redisService = redisService;
        }

        public async Task<CommandResult<bool>> Create(CreateCommentCommand command)
        {
            var ret = await commentRepository.Create(command);
            switch (ret)
            {
                case 1:
                    await redisService.Remove("GetDetail_" + command.OrderId);
                    return CommandResult<bool>.Success(true);
                case 2:
                    return CommandResult<bool>.Failure("用户信息不匹配");
                case 3:
                    return CommandResult<bool>.Failure("该订单已经评论过了");
                case 4:
                    return CommandResult<bool>.Failure("订单信息错误");
                default:
                    return CommandResult<bool>.Failure("请求出错");

            }

        }

        public async Task<int> GetCounts(int productId)
        {
            var res = 0;
            var ds = await commentRepository.GetCounts(productId);
            if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
            {
                res = Convert.ToInt32(ds.Tables[0].Rows[0]["totalCount"]);
            }
            return res;
        }

        public async Task<List<CommentViewModel>> QueryComments(QueryCommentCriteria criteria)
        {
            var queryList = new List<CommentViewModel>();
            var ds = await commentRepository.QueryComments(criteria);
            if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    queryList.Add(new CommentViewModel()
                    {
                        Id = Convert.ToInt32(dr["Id"]),
                        CommentLevel = Convert.ToInt32(dr["CommentLevel"]),
                        NickName = dr["NickName"].ToString(),
                        CreateTime = Convert.ToDateTime(dr["CreateTime"]).ToString("yyyy-MM-dd HH:mm:ss"),
                        HeadImgUrl = dr["HeadImgUrl"].ToString(),
                        CommentMsg = dr["CommentMsg"].ToString()
                    });
                }


            }
            return queryList;
        }
    }
}
